﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AopFilters
{
    /// <summary>
    /// 资源AOP （最适合做缓存）【异步版本】
    /// </summary>
    public class KmAsyncResourceFilterAttribute : Attribute, IAsyncResourceFilter
    {
        public static Dictionary<string, object> CacheDic = new Dictionary<string, object>();
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            if (context.IfIgnoreFilter(typeof(KmAsyncResourceFilterAttribute)))
            {
                await next.Invoke();
                return;
            }
            Console.WriteLine("【ResourceFilter】开始...");
            //将请求路径作为缓存key， 还没请求资源时，先判断是否有缓存，如果有直接返回数据，不用进入方法了
            string key = context.HttpContext.Request.Path;
            if (CacheDic.ContainsKey(key))
            {
                IActionResult result = CacheDic[key] as IActionResult;
                context.Result = result;//只要对Result赋值了，就不会继续执行了
            }
            else
            {
                ResourceExecutedContext context1 = await next.Invoke();//执行 控制器构造函数、接口方法
                context.Result = context1.Result;
                CacheDic[key] = context.Result;
                Console.WriteLine("【ResourceFilter】结束...");
            }
        }
    }
}
